<template>
  <!-- Swiper轮播图 - Coverflow效果 -->
  <div class="w-screen -mx-[11vw] relative">
    <div class="mb-6 w-[116vw] flex justify-center" style="margin: 0 auto; padding: 0;">
      <!-- 自定义导航箭头 - MOVED HERE -->
      <!-- 2. 移除箭头上的 Tailwind left/right 定位类，因为我们将用 scoped CSS 控制 -->
      <div @click="slidePrev" class="custom-nav-prev absolute top-1/2 z-[9999] transform -translate-y-1/2 bg-white rounded-full w-12 h-12 flex items-center justify-center shadow-lg cursor-pointer hover:bg-gray-100 hover:scale-110 transition-all duration-200" style="display: flex !important; opacity: 1 !important;">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#991E29" class="w-8 h-8">
          <path d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z"></path>
        </svg>
      </div>
      <div @click="slideNext" class="custom-nav-next absolute top-1/2 z-[9999] transform -translate-y-1/2 bg-white rounded-full w-12 h-12 flex items-center justify-center shadow-lg cursor-pointer hover:bg-gray-100 hover:scale-110 transition-all duration-200" style="display: flex !important; opacity: 1 !important;">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#991E29" class="w-8 h-8">
          <path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"></path>
        </svg>
      </div>
      <div class="relative w-[2320px]">
        <swiper
            :effect="'coverflow'"
            :grabCursor="true"
            :centeredSlides="true"
            :slidesPerView="'auto'"
            :breakpoints="{
            '320': { slidesPerView: 1.1, spaceBetween: 60 },
            '640': { slidesPerView: 1.3, spaceBetween: 70 },
            '1024': { slidesPerView: 1.5, spaceBetween: 80 },
            '1440': { slidesPerView: 1.8, spaceBetween: 90 }
          }"
            :spaceBetween="120"
            :initialSlide="2"
            :coverflowEffect="{
            rotate: 0,
            stretch: 0,
            depth: 0,
            modifier: 1,
            slideShadows: false
          }"
            :loop="slides.length >= 4"
            :loopedSlides="slides.length >= 4 ? 4 : 0"
            :pagination="{ clickable: true }"
            :navigation="false"
            :autoplay="{ delay: 3000, disableOnInteraction: false }"
            :modules="[EffectCoverflow, Navigation, Pagination, Autoplay]"
            @swiper="onSwiper"
            class="mySwiper"
        >
          <swiper-slide v-for="slide in slides" :key="slide.id" class="relative cursor-pointer" @click="handleSlideClick(slide)">
            <img :src="slide.image" :alt="slide.title" />
            <div class="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white p-4">
              <h3 class="text-xl font-bold">{{ slide.title }}</h3>
              <p>{{ slide.description }}</p>
            </div>
          </swiper-slide>
        </swiper>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { EffectCoverflow, Navigation, Pagination, Autoplay } from "swiper/modules";

// Import Swiper styles
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/effect-coverflow';

// 导入API配置
import { homeApi, API_BASE_URL } from '@/utils/api';

// Vue Router实例
const router = useRouter();

// 定义emit
const emit = defineEmits(['api-error'])

// 轮播图数据
const slides = ref([]);
const error = ref(null);

// 定义一个响应式引用来存储Swiper实例
const swiperInstance = ref(null);

// 获取首页轮播图数据
const fetchHomeSlides = async () => {
  error.value = null;
  try {
    const response = await homeApi.getTopCarouselData();
    
    // 处理API返回的不同数据结构
    let slidesData = [];
    if (Array.isArray(response)) {
      slidesData = response;
    } else if (response && response.data && Array.isArray(response.data)) {
      slidesData = response.data;
    } else if (response && response.slides && Array.isArray(response.slides)) {
      slidesData = response.slides;
    } else {
      throw new Error('API返回的数据格式不正确');
    }

    slides.value = slidesData.map(slide => ({
      id: slide.id || slide.slide_id,
      title: slide.title || '',
      description: slide.description || '',
      image: slide.image_url || slide.image || '',
      link: slide.link_url || slide.link || ''
    }));

    // 如果没有数据，显示错误信息
    if (slides.value.length === 0) {
      error.value = '暂无轮播图数据';
      slides.value = [];
    }
  } catch (err) {
    console.error('TopCarousel: API请求失败:', err);
    // 触发API错误事件，让父组件处理
    emit('api-error', err);
  }
};



// 页面加载时获取数据
onMounted(async () => {
  try {
    slides.value = [];
    await fetchHomeSlides();

    // 等待一个帧，确保 DOM 已经更新
    await nextTick();

    // 更新Swiper实例
    if (swiperInstance.value) {
      swiperInstance.value.update();
    }
  } catch (error) {
    console.error('Error in onMounted:', error);
  }
});

const onSwiper = (swiper) => {
  // 存储Swiper实例到响应式引用中
  swiperInstance.value = swiper;
};

// 向前滑动方法
const slidePrev = () => {
  if (swiperInstance.value) {
    swiperInstance.value.slidePrev();
  }
};

// 向后滑动方法
const slideNext = () => {
  if (swiperInstance.value) {
    swiperInstance.value.slideNext();
  }
};

// 处理幻灯片点击
const handleSlideClick = (slide) => {
  console.log('Slide clicked:', slide.title);
  // 这里可以添加点击幻灯片后的操作，比如导航到详情页面
  alert(`点击了幻灯片: ${slide.title}`);
};
</script>

<style scoped>
/* 原始轮播图样式 */
.mySwiper {
  width: 100%;
  padding-top: 40px;
  padding-bottom: 40px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
}

.mySwiper .swiper-slide {
  background-position: center;
  background-size: cover;
  height: 500px;
  width: 2580px;
  transform: scale(0.8);
  transition: all 0.3s ease;
  text-align: center;
  margin: 0 auto;
  border-radius: 12px;
  overflow: hidden;
  opacity: 0.8;
  filter: blur(0.5px) grayscale(20%);
  box-shadow: 0 15px 35px rgba(0,0,0,0.25);
}

  .mySwiper .swiper-slide-active {
    transform: scale(1);
    z-index: 20;
    opacity: 1;
    box-shadow: 0 20px 40px rgba(0,0,0,0.4);
    filter: blur(0) grayscale(0%) brightness(105%);
    border: 4px solid rgba(255,255,255,0.8);
    transition: all 0.7s ease;
    width: 2200px;
    margin: 0 auto;
    position: relative;
    left: 0;
    right: 0;
}


@media (max-width: 1200px) {
  .mySwiper .swiper-slide { /* 增加 .mySwiper 前缀 */
    height: 315px;
    width: 1200px;
    transform: scale(0.4) perspective(500px) rotateY(8deg); /* 减少缩小比例和倾斜角度 */
    opacity: 0.6;
    filter: blur(1px) grayscale(20%);
    box-shadow: 0 8px 25px rgba(0,0,0,0.2);
  }

  .mySwiper .swiper-slide-active { /* 增加 .mySwiper 前缀 */
    transform: scale(1.6) perspective(500px) rotateY(0deg); /* 调整激活尺寸 */
    opacity: 1;
    box-shadow: 0 20px 40px rgba(0,0,0,0.4);
    filter: blur(0) grayscale(0%) brightness(105%);
    border: 3px solid white;
    width: 1800px; /* 调整宽度 */
  }

  .mySwiper {
    padding-top: 40px;
    padding-bottom: 40px;
  }
  .custom-nav-prev,
  .custom-nav-next {
    display: none !important;
  }
}

.swiper-slide {
  background-color: #f5f5f5; /* 保留背景色 */
}

.swiper-slide img {
  display: block;
  width: 100%;
  height: 84%;
  object-fit: cover;
  object-position: top center;
  transition: all 0.7s ease;
  margin: 0 auto;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}

.mySwiper .swiper-slide-active:hover img {
  filter: brightness(115%) contrast(105%);
}

/* 自定义导航箭头样式 */
.custom-nav-prev,
.custom-nav-next {
  position: absolute !important; /* 确保是 absolute */
  top: 50% !important;
  transform: translateY(-50%) !important;
  width: 44px !important; /* Tailwind w-12 is 3rem (48px), h-12 is 3rem (48px). Choose one or the other or sync. */
  height: 44px !important;/* Let's assume 44px is intentional. */
  background-color: white !important;
  border-radius: 50% !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2) !important;
  transition: all 0.3s ease !important;
  opacity: 1 !important;
  visibility: visible !important;
  z-index: 9999 !important; /* 确保在最上层 */
  cursor: pointer !important;
}

.custom-nav-prev {
  /* 3. 调整 left 值 */
  /* 11vw (父元素的负margin) + 2rem (期望的视口边距) */
  left: calc(14vw + 4rem) !important;
}

.custom-nav-next {
  /* 3. 调整 right 值 */
  right: calc(-2vw + 4rem) !important;
}

.custom-nav-prev:hover,
.custom-nav-next:hover {
  background-color: #f8f8f8 !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25) !important;
  transform: translateY(-50%) scale(1.05) !important;
}

/* 分页指示器样式 */
:deep(.swiper-pagination) {
  bottom: 10px !important;
  z-index: 100 !important;
  position: absolute !important;
}

:deep(.swiper-pagination-bullet) {
  background-color: white !important;
  opacity: 0.7 !important;
  width: 10px !important;
  height: 10px !important;
  transition: all 0.3s ease !important;
  display: inline-block !important;
  margin: 0 4px !important;
}

:deep(.swiper-pagination-bullet-active) {
  background-color: #991E29 !important;
  opacity: 1 !important;
  width: 12px !important;
  height: 12px !important;
}
</style>
